package com.xiaohao.employee_attendance.interceptor;

import com.xiaohao.employee_attendance.bean.User;
import com.xiaohao.employee_attendance.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 小浩
 * @date 2019-03-06 22:25
 * @package com.xiaohao.employee_attendance.interceptor
 * @description
 */
@Component
public class AutoLoginIntercepetor implements HandlerInterceptor {
    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String autoLogin = "";
        for (Cookie cookie : request.getCookies()) {
            if ("autoLogin".equals(cookie.getName())) {
                autoLogin = cookie.getValue();
            }
        }
        if ("autoLogin".equals(autoLogin)) {
            String username = "", password = "";
            for (Cookie cookie : request.getCookies()) {
                if ("username".equals(cookie.getName())) {
                    username = cookie.getValue();
                }
                if ("password".equals(cookie.getName())) {
                    password = cookie.getValue();
                }
            }
            User userByName = userService.findUserByAccount(username);
            if (userByName == null) {
                request.setAttribute("fail", "用户名不正确！");
                request.getRequestDispatcher("/login").forward(request, response);
            }
            if (password.equals(userByName.getPassword())) {
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute("user", userByName);
                httpSession.setAttribute("loginDate", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒")));
                response.sendRedirect("/nav");
            } else {
                request.setAttribute("fail", "密码不正确！");
                request.getRequestDispatcher("/login").forward(request, response);
            }
        }
        return true;
    }
}
